package com.leaf.lowcode.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.leaf.lowcode.utils.RegularInstance;
import com.leaf.lowcode.utils.RsaUtil;
import com.tencent.welink.iot.SubDeviceDTO;
import com.tencent.welink.iot.WelinkHttp;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Base64;
import java.util.List;


/**
 * 道一云电投一一样的
 */
@Component
public class DaoYiYunApiEventSend {
    /**
     * 定时获取道一云接口
     *
     * @throws Exception
     */
    @Scheduled(initialDelay = 6 * 1000, fixedRate = 60 * 1000)
    public void execute() throws Exception {


        /**
         * 获取token
         */
        QueryToken queryToken = new QueryToken();

        System.out.println("==================启动=================");

        //    public static void main(String[] args) throws Exception {

        //公钥
        String publicKey = new RsaUtil("rsapublic.xml").Key();

        //  System.out.println(publicKey);

        /**
         * 测试数据
         */
        String msg = " {\n" +
                "            \"visitAppointedTimeStart\":\"2021-01-01\",\n" +
                "                \"visitAppointedTimeEnd\":\"2021-12-01\",\n" +
                "            \"visitorUserName\":\"\"\n" +
                "        }";
        /**
         * 加密解密
         */
        EncrypRSA rsa = new EncrypRSA();
        byte[] ciphertextPublic = rsa.encrypt(publicKey, msg, "PUBLIC");
        String json = new String(Base64.getEncoder().encode(ciphertextPublic));

        //String cleartextPublic = rsa.decryptToString(publicKey,  new String(Base64.getEncoder().encode(ciphertextPrivate)),EncrypRSA.PUBLIC);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交

        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //添加参数developerId
        MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
        multiValueMap.add("json", json);

        //封装
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(multiValueMap, headers);
        //post请求

        String token = queryToken.execute();
        System.out.println("token" + token);

        /**
         * 电投一接口
         */


        String url = "https://work.spic.com.cn:8443/mgr/visitor/open/getRecord.do?token=";
//        String url="https://workuat.spic.com.cn/mgr/visitor/open/getRecord.do?token=";
        String urltoken = url + token;

        ResponseEntity<String> responseEntity = restTemplate.exchange(urltoken, method, request, String.class);
        //   提交

        String body = responseEntity.getBody();
        System.out.println(responseEntity.getStatusCode());
        System.out.println(responseEntity.getStatusCodeValue());
        System.out.println(responseEntity.getHeaders());
        System.out.println("=================" + body + "===============================");

        if (body.contains("token超时")) {
            queryToken = new QueryToken();
            token = queryToken.execute();
            urltoken = url + token;
            responseEntity = restTemplate.exchange(urltoken, method, request, String.class);
            body = responseEntity.getBody();
        }

        JSONObject objects = JSON.parseObject(body);
        JSONArray visitinfoList = (JSONArray) ((JSONObject) objects.get("data")).get("data");

        //通过全量数据，获得增量数据
        //1.入库
        //1.1入库前，做一个判断，id是够存在，如果有重复的访客，id是事件id。
        //1.1.1 存在。。。。
        //1.1.2 不存在 入库
        //1.1.3 推送海康威视门禁，停车，吃饭
        //1.1.1.4推送成功，可以用身份证刷门禁进入国电投


        /**
         *
         */


        /**
         * 后台获取的数据
         */
        //String  visitString="{\"code\":\"0\",\"desc\":\"查询成功\",\"data\":{\"data\":[{\"approvalContent\":\"部门归档\",\"approvalStatus\":1,\"beVisitUserDept\":\"项目测试组\",\"beVisitUserId\":\"e7956ad0193f70176d3022704be0d81f\",\"beVisitUserName\":\"腾讯-程雨\",\"carNumber\":\"\",\"dine\":0,\"fourteenArea\":\"上海\",\"fourteenTouch\":0,\"id\":\"66d879d92e224881b1c37640da10cd9e\",\"idNumber\":\"21840486464649464X\",\"isDine\":0,\"isolationLiving\":0,\"precontractType\":0,\"status\":31,\"travelMode\":0,\"visitAffairs\":\"开会\",\"visitAppointedTime\":\"2021-11-24 09:00:00.0\",\"visitCompany\":\"项目测试组\",\"visitTarget\":\"12\",\"visitorUserIdNumber\":\"21840486464649464X\",\"visitorUserName\":\"同行p\",\"visitorUserPhone\":\"14531818464\"},{\"approvalContent\":\"部门归档\",\"approvalStatus\":1,\"beVisitUserDept\":\"项目测试组\",\"beVisitUserId\":\"e7956ad0193f70176d3022704be0d81f\",\"beVisitUserName\":\"腾讯-程雨\",\"carNumber\":\"\",\"dine\":0,\"fourteenArea\":\"北京\",\"fourteenTouch\":0,\"id\":\"e18149bf796540f884cfffdc2dc4bcb9\",\"idNumber\":\"54454566451616545X\",\"isDine\":0,\"isolationLiving\":0,\"precontractType\":0,\"status\":31,\"travelMode\":0,\"visitAffairs\":\"开会\",\"visitAppointedTime\":\"2021-11-19 00:00:00.0\",\"visitCompany\":\"道一\",\"visitTarget\":\"12\",\"visitorUserIdNumber\":\"54454566451616545X\",\"visitorUserName\":\"程雨\",\"visitorUserPhone\":\"14578546156\"},{\"approvalContent\":\"\",\"approvalStatus\":1,\"beVisitUserDept\":\"项目测试组\",\"beVisitUserId\":\"e7956ad0193f70176d3022704be0d81f\",\"beVisitUserName\":\"腾讯-程雨\",\"carNumber\":\"\",\"dine\":0,\"fourteenArea\":\"北京\",\"fourteenTouch\":0,\"id\":\"08147336478a48ec85709769f0caed6f\",\"idNumber\":\"210821198507035374\",\"isDine\":0,\"isolationLiving\":0,\"precontractType\":0,\"status\":31,\"travelMode\":0,\"visitAffairs\":\"开会\",\"visitAppointedTime\":\"2021-11-13 09:00:00.0\",\"visitCompany\":\"项目测试组\",\"visitTarget\":\"12楼信息化\",\"visitorUserIdNumber\":\"210821198507035374\",\"visitorUserName\":\"腾讯-张华刚\",\"visitorUserPhone\":\"17701151500\"},{\"approvalContent\":\"部门归档\",\"approvalStatus\":1,\"beVisitUserDept\":\"项目测试组\",\"beVisitUserId\":\"e7956ad0193f70176d3022704be0d81f\",\"beVisitUserName\":\"腾讯-程雨\",\"carNumber\":\"京b218464\",\"dine\":0,\"fourteenArea\":\"北京\",\"fourteenTouch\":0,\"id\":\"16f99cd4e39247d08c3ccd8ea6b27b8e\",\"idNumber\":\"\",\"isDine\":0,\"isolationLiving\":0,\"precontractType\":0,\"status\":31,\"travelMode\":3,\"visitAffairs\":\"开会\",\"visitAppointedTime\":\"2021-09-18 09:00:00.0\",\"visitCompany\":\"广东\",\"visitTarget\":\"12楼\",\"visitorUserIdNumber\":\"\",\"visitorUserName\":\"黄飞鸿\",\"visitorUserPhone\":\"14554816494\"}]}}\n";


//        JSONObject visitinfoList = JSONObject.parseObject(visitString);
//          JSONArray jsonobject= (JSONArray) ((JSONObject) visitinfoList.get("data")).get("data");
        System.out.println(visitinfoList);


        //上传微瓴
     /*  List<SubDeviceDTO> subDeviceDTOList = RegularInstance.subDeviceDTOList;
            if (subDeviceDTOList != null) {
                for (SubDeviceDTO dto : subDeviceDTOList) {
                    String pid = dto.getPid();
                    String sn = dto.getSn();
                    String din = dto.getDin();

                    if (sn.equals("dyyfkgdtsn")) {
                        //  System.out.println("======================门禁卡========================"+readerdoorstatesend.getIndexCode());

                       for(int i=0;i<jsonobject.size();i++){
                           JSONObject visitor= (JSONObject) jsonobject.get(i);
                        JSONObject standardData = new JSONObject();
                        standardData.put("reportTs", System.currentTimeMillis());
                        JSONObject profile = new JSONObject();
                        profile.put("modelId", 200700);
                        profile.put("poiCode", "w0717006");
                        profile.put("appType","visitor");
                        standardData.put("profile", profile);
                        WelinkHttp wh = new WelinkHttp(RegularInstance.registerData1, RegularInstance.loginData);
                        JSONObject events = new JSONObject();
                        JSONObject event = new JSONObject();
                        event.put("eventType", 1);
                        event.put("eventTs", System.currentTimeMillis());
                        event.put("describe", "");
                        event.put("id",visitor.get("id"));

                        event.put("visitorUserIdNumber",visitor.get("visitorUserIdNumber"));

                           event.put("visitorUserPhone",visitor.get("visitorUserPhone"));

                           event.put("beVisitUserDepts",visitor.get("beVisitUserDepts"));

                           event.put("visitorUserName",visitor.get("visitorUserName"));

                           event.put("beVisitUserName",visitor.get("beVisitUserName"));

                           event.put("visitAppointedTime",visitor.get("visitAppointedTime"));

                           event.put("visitAffairs",visitor.get("visitAffairs"));

                           event.put("beVisitUserId",visitor.get("beVisitUserId"));

                           event.put("isDine",visitor.get("isDine"));

                           event.put("carNumber",visitor.get("carNumber"));

                           event.put("status",visitor.get("status"));
                        events.put("appointment",event);
                        standardData.put("events",events);
                        standardData.put("properties", new JSONObject());
                        //standardData.put("properties", "{}");
                        try {
                              System.out.println("上传数据");
                            String devRunEvent = JSONObject.toJSONString(standardData, SerializerFeature.WriteMapNullValue);
                              System.out.println("发送设备运行时事件数据==" + devRunEvent);
                               System.out.println("--------------------------------开始传输设备运行时事件数据");
                            wh.sendMessage(RegularInstance.loginData.load(), 80000, Long.parseLong(din), devRunEvent, true);
                            System.out.println("ddddddd"+devRunEvent+"ssssss");
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println("设备运行时事件数据传输出现异常");
                        }
                    }*/
    }
}




